package com.pagoda.nerp.web.common.buildTree;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 构建树
 * <p>
 * 必须对 Code 进行排序,order by length(tagCode), tagCode
 * </p>
 *
 * @author Yd on  2017-11-30
 * @Description：
 **/
public class TreeBuild {
    private static Logger log = LoggerFactory.getLogger(TreeBuild.class);

    /**
     * 行数据 必修保证 编码的一致性，重复会覆盖
     * @param list
     * @param <T>
     * @return
     */
    public static <T extends TreeNode> List<Tree> buildTree(List<T> list) {
        List<Tree> rootTree = new ArrayList<Tree>();//根节点
        if (CollectionUtils.isEmpty(list)) {//集合为空，直接返回
            return rootTree;
        }

        Map<String, Tree> tempMap = new HashMap<String, Tree>(list.size());
        int minLength = list.get(0).getCode().length();//初始化，根 层的编码长度
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getCode().length() < minLength) {
                minLength = list.get(i).getCode().length();
            }
            tempMap.put(list.get(i).getCode(), new Tree(list.get(i)));
        }
        //判断 编码是否重复
        if(tempMap.size()!=list.size()){
            log.info("存在编码重复");
        }
        //从后遍历 设置
        for (int i = list.size() - 1; i >= 0; i--) {
            //1.再次判断 是否是 根节点
            if (list.get(i).getCode().length()!=minLength){
                //2-1.获取父节点编码
                String parentCode = list.get(i).getParentCode();
                if (tempMap.get(parentCode) == null) {//不存在
                    log.info("该编码-" + list.get(i).getCode() + "-不存在对应的父节点编码-" + parentCode);
                    continue;
                }else {
                    //2-2.设置父节点 的孩子
                    tempMap.get(parentCode).getchildren().add(0,tempMap.get(list.get(i).getCode()));
                }

            }else{
                rootTree.add(0,tempMap.get(list.get(i).getCode()));
                continue;
            }
        }

        return rootTree;
    }

}
